<template>
  <a-modal
    :visible.sync="modalVisible"
    title="数据筛选"
    width="1200px"
    :maskClosable="false"
    :destroyOnClose="true"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-row style="height: 510px;">
      <a-col :span="7" style="border-right: 1px solid #aaa; padding-right: 20px; height: 100%; overflow-y: auto;">
        <a-input-search v-model="searchValue" placeholder="请搜索" @change="onTreeSearch" />
        <Empty v-if="!searchTreeData[0] || !searchTreeData[0].children.length" style="margin-top: 120px;" />
        <a-tree
          v-else
          :tree-data="searchTreeData"
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :replaceFields="{ title: 'orgName', key: 'orgId' }"
          @expand="onExpand"
          @select="onTreeSelected"
        >
          <template slot="orgName" slot-scope="{ orgName }">
            <div v-if="orgName.indexOf(searchValue) > -1" :title="orgName" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;width: 280px;">
              {{ orgName.substr(0, orgName.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ orgName.substr(orgName.indexOf(searchValue) + searchValue.length) }}
            </div>
            <div v-else :title="orgName" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;width: 280px;">{{ orgName }}</div>
          </template>
        </a-tree>
      </a-col>
      <a-col :span="17" style="padding-left: 20px;">
        <div style="display: flex;">
          <a-form :form="form" layout="inline" style="width: 82%;">
            <a-form-item label="组织名称">
              <a-input v-decorator="['orgName']" autocomplete="off" />
            </a-form-item>
            <a-form-item label="项目状态">
              <a-select v-decorator="['projectStatusList']" mode="multiple" showArrow optionFilterProp="children" style="width: 100%;">
                <a-select-option value="ONGOING" title="施工准备阶段">施工准备阶段</a-select-option>
                <a-select-option value="START_WORKING" title="在建">在建</a-select-option>
                <a-select-option value="SHUTDOWN" title="停工">停工</a-select-option>
                <a-select-option value="SUSPENDED" title="停缓建">停缓建</a-select-option>
                <a-select-option value="MAINTENANCE_PERIOD" title="维保期">维保期</a-select-option>
                <a-select-option value="MAINTENANCE_PERIOD_CLOSE" title="维保期截止">维保期截止</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="项目业态">
              <a-select v-decorator="['formatIdList']" mode="multiple" showArrow optionFilterProp="children" style="width: 100%;">
                <a-select-option v-for="item in industryStatusOptions" :key="item.code" :value="item.code" :title="item.name">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="项目类型">
              <a-select v-decorator="['projectTypeIds']" mode="multiple" showArrow optionFilterProp="children" style="width: 100%;">
                <a-select-option v-for="item in typesOptions" :key="item.typeId" :value="item.typeId" :title="item.typeName">{{item.typeName}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="承包模式">
              <a-select v-decorator="['contractModelIdList']" mode="multiple" optionFilterProp="children" showArrow style="width: 100%;">
                <a-select-option v-for="item in contractModeOptions" :key="item.code" :value="item.id" :title="item.name">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
          <div style="width: 18%; text-align: right; padding-top: 5px;">
            <a-button type="primary" style="margin-right: 12px;" @click="onSearch">查询</a-button>
            <a-button type="default" @click="onReset">重置</a-button>
          </div>
        </div>
        <div style="height: 60px; overflow-y: auto; margin-bottom: 10px;">
          <a-tag
            v-for="item in selectedRows"
            :key="item.orgId"
            color="#108ee9"
            closable
            style="margin: 3px;"
            @close="onTagClose(item)"
          >
            {{item.levelName}}
          </a-tag>
        </div>
        <a-table
          rowKey="orgId"
          bordered
          :loading="loading"
          :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
          :columns="[
            { title: '序号', width: 70, customRender: (text, record, index) => index + 1 },
            { title: '组织名称', dataIndex: 'orgName' },
            { title: '层级', dataIndex: 'levelName' },
          ]"
          :data-source="tableList"
          :scroll="{ y: 240 }"
          :pagination="{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '30', '40', '100'],
            onChange: onPageChange,
            showTotal: () => `共搜索到${pagination.total}条数据`
          }"
        />
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { mapState } from 'vuex'
import { businessQueryTreeList, businessQueryList } from '@/api/dataFilter'
import { getProjectFrom, getLabel } from '@/api/project/projects'
import { getProjectypesList } from '@/api/project/projectypes'

export default {
  name: 'businessFilterModal',
  components: { Empty },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      orgId: !!sessionStorage.getItem('ycloud-user_info') ? JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.currentPost.id : '',
      form: this.$form.createForm(this, {}),
      treeData: [],
      treeDataList: [],
      searchTreeData: [],
      treeOrgId: '',
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      tableList: [],
      totalTableList: [],
      originTableList: [],
      selectedRowKeys: [],
      industryStatusOptions: [],
      typesOptions: [],
      contractModeOptions: [],
      loading: false,
      pagination: {
        current: 1,
        total: 0
      },
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      businessSearchConditions: state => state.user.businessSearchConditions
    }),
    modalVisible: {
      get: function(){
        return this.visible
      },
      set: function(val){
        this.$emit('update:visible', val)
      }
    },
    selectedRows(){
      return this.selectedRowKeys.map(key => this.totalTableList.find(item => item.orgId === key)).filter(item => !!item)
    }
  },
  watch: {
    visible(val){
      if(val){
        this.init()
      }
    }
  },
  methods: {
    init(){
      if([...this.businessSearchConditions.detSet, ...this.businessSearchConditions.orgSet].length < this.tableList.length){
        this.selectedRowKeys = [...this.businessSearchConditions.detSet, ...this.businessSearchConditions.orgSet]
      }else{
        this.selectedRowKeys = []
      }
    },
    getFormOptions(){
      // 项目业态选项
      getProjectFrom().then(res => {
        if(res.success){
          this.industryStatusOptions = res.data
        }
      })
      // 项目类型选项
      getProjectypesList({
        typeStatusCode: 1
      }).then(res => {
        if(res.success){
          this.typesOptions = res.data
        }
      })
      // 承包模式
      getLabel({
        type: 3
      }).then(res => {
        if(res.success){
          this.contractModeOptions = res.data
        }
      })
    },
    filterTreeData(data){
      return data.map(item => ({
        ...item,
        scopedSlots: { title: 'orgName' },
        children: item.children && item.children.length ? this.filterTreeData(item.children) : []
      }))
    },
    // 获取树形数据
    getTreeList(){
      businessQueryTreeList({
        orgId: this.orgId
      }).then(res => {
        if(res.success){
          this.searchValue = ''
          this.treeData = this.filterTreeData(res.data)
          this.searchTreeData = this.treeData
          this.generateList(res.data)
        }
      })
    },
    // 获取表格数据
    getTableList(params = {}){
      this.loading = true
      if(this.treeOrgId){
        params.treeOrgId = this.treeOrgId
      }
      businessQueryList({
        orgId: this.orgId,
        ...params
      }).then(res => {
        if(res.success){
          this.tableList = res.data
          if(!this.treeOrgId) this.originTableList = res.data
          this.totalTableList = this.totalTableList.filter(item => !res.data.some(i => i.orgId === item.orgId)).concat(res.data)
          this.pagination = {
            ...this.pagination,
            total: res.data.length
          }
        }
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    // 平铺树形数组
    generateList(data){
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        this.treeDataList.push({ orgId: node.orgId, orgName: node.orgName })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    // 返回父级key
    getParentKey(key, tree){
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.orgId === key)) {
            parentKey = node.orgId;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    searchFilterTreeData(data){
      data = data || this.treeData[0].children
      return data.filter(item => this.expandedKeys.some(key => key === item.orgId) || item.orgName.indexOf(this.searchValue) > -1).map(item => {
        if (item.children && item.children.length) {
          return {
            ...item,
            children: this.searchFilterTreeData(item.children)
          }
        } 
        return item
      })
    },
    // 树形菜单搜索
    onTreeSearch(event){
      const expandedKeys = this.treeDataList.map(item => {
        if (item.orgName.indexOf(event.target.value) > -1) {
          return this.getParentKey(item.orgId, this.treeData);
        }
        return null;
      }).filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys: !!this.searchValue ? expandedKeys : [],
        searchValue: event.target.value,
        autoExpandParent: !!this.searchValue,
      })
      this.searchTreeData = !!this.searchValue ? [{
          ...this.treeData[0],
          children: this.searchFilterTreeData(this.treeData[0].children)
        }] : this.treeData
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    // 树形选中
    onTreeSelected([selectedKey]){
      this.treeOrgId = selectedKey
      this.onReset()
    },
    // 表格列表勾选
    onSelectChange(values){
      this.selectedRowKeys = values
    },
    // 分页切换
    onPageChange(value){
      this.pagination.current = value
    },
    // Tag标签关闭
    onTagClose(data){
      this.selectedRowKeys = this.selectedRowKeys.filter(key => key !== data.orgId)
    },
    // 查询
    onSearch(){
      const params = {}
      Object.keys(this.form.getFieldsValue()).map(key => {
        if(this.form.getFieldsValue()[key] instanceof Array && this.form.getFieldsValue()[key].length > 0){
          params[key] = this.form.getFieldsValue()[key]
        }else if(this.form.getFieldsValue()[key] != undefined){
          params[key] = this.form.getFieldsValue()[key]
        }
      })
      this.getTableList(params)
      this.pagination.current = 1
    },
    // 重置
    onReset(){
      this.form.resetFields()
      this.getTableList()
      this.pagination.current = 1
    },
    // 确定
    handleOk(){
      const rows = !!this.selectedRows.length ? this.selectedRows : this.originTableList
      this.$store.commit('SET_BUSINESS_SEARCH_CONDITIONS', {
        detSet: rows.filter(item => item.type == 3).map(item => item.orgId),
        orgSet: rows.filter(item => item.type != 3).map(item => item.orgId)
      })
      this.handleCancel()
    },
    // 关闭弹窗
    handleCancel(){
      this.modalVisible = false
      this.treeOrgId = ''
      this.onReset()
      // 清空树形搜索框
      Object.assign(this, {
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: false,
      })
      this.searchTreeData = this.treeData
    },
  },
  mounted(){
    this.getFormOptions()
    this.getTreeList()
    this.getTableList()
  }
}
</script>
<style lang="less" scoped>
  /deep/ .ant-form-item{
    margin-right: 0;
    .ant-form-item-label{
      width: 100px !important;
    }
    .ant-form-item-control-wrapper{
      width: 200px;
    }
  }
</style>